import { useEffect } from 'react'
import { message } from 'antd'
import { setUserInfo, type UserInfo } from '../../utils/auth'

const CLIENT_ID = 'fb2428e600444232b42e6e440fa526a268a93e12daa6ab0bea2f938b47cdcfb6'
const CLIENT_SECRET = 'a97b39759b9682209bac55f479fbef559dd053775d678af162147df8b014a2d6'

export default function GiteeCallback() {
  useEffect(() => {
    const params = new URLSearchParams(window.location.search)
    const code = params.get('code')
    if (!code) {
      message.error('缺少 code 参数')
      return
    }
    ;(async () => {
      try {
        // 前端直接换 token（不推荐生产使用）
        const tokenRes = await fetch('https://gitee.com/oauth/token', {
          method: 'POST',
          headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
          body: new URLSearchParams({
            grant_type: 'authorization_code',
            code,
            client_id: CLIENT_ID,
            client_secret: CLIENT_SECRET,
            redirect_uri: `${window.location.origin}/auth/gitee/callback`
          })
        })
        const tokenData = await tokenRes.json()
        if (!tokenRes.ok || !tokenData.access_token) {
          throw new Error(tokenData.error || '换取 token 失败')
        }
        const accessToken = tokenData.access_token as string
        const userRes = await fetch(`https://gitee.com/api/v5/user?access_token=${encodeURIComponent(accessToken)}`)
        const user = await userRes.json()
        const userInfo: UserInfo = {
          username: user?.name || user?.login || 'gitee_user',
          role: 0,
          userId: Number(user?.id) || Date.now(),
          token: accessToken
        }
        setUserInfo(userInfo)
        message.success(`Gitee 登录成功，欢迎 ${userInfo.username}`)
        window.location.replace('/')
      } catch (e) {
        console.error(e)
        message.error('Gitee 登录失败')
        window.location.replace('/login')
      }
    })()
  }, [])

  return (
    <div style={{ height: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
      正在完成 Gitee 登录...
    </div>
  )
}


